import os
import pygame
import time
import threading

PAUSE_MUSIC = 1
UNPAUSE_MUSIC = 2
ADD_VOLUME = 3
MIN_VOLUME = 4

pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.init()
pygame.mixer.init()


def play_music(file_path):
    pygame.mixer.music.load(file_path)
    pygame.mixer.music.play(loops=0, start=0.0)


def pause_music():
    pygame.mixer.music.pause()


def unpause_music():
    pygame.mixer.music.unpause()


def stop_music():
    pygame.mixer.music.stop()


def play_songs(path):
    # set_endevent设置音频播放结束事件,通知继续下一个
    pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)
    # 当前目录所有音乐文件
    files = os.listdir(path)
    while True:
        for file in files:
            play_music(os.path.join(path, file))
            done = False
            while not done:
                for event in pygame.event.get():
                    if event.type == pygame.constants.USEREVENT:
                        done = True


def play_song_action(cmd_to_song):
    if (cmd_to_song == PAUSE_MUSIC):
        pygame.mixer.music.pause()
    elif (cmd_to_song == UNPAUSE_MUSIC):
        pygame.mixer.music.unpause()
    elif (cmd_to_song == ADD_VOLUME):
        volume = pygame.mixer.music.get_volume()
        volume += 0.1
        pygame.mixer.music.set_volume(volume)
    elif (cmd_to_song == MIN_VOLUME):
        volume = pygame.mixer.music.get_volume()
        volume -= 0.1
        pygame.mixer.music.set_volume(volume)
    else:
        pass


if __name__ == "__main__":
    music_thread = threading.Thread(
        target=play_songs, args=("/home/cmh/Music/",), daemon=True)
    music_thread.start()
    time.sleep(2)
    play_song_action(PAUSE_MUSIC)
    time.sleep(2)
    play_song_action(UNPAUSE_MUSIC)
